//app.js
   
App({
    onLaunch: function() {
            
        if (!wx.cloud) {
            console.error('请使用 2.2.3 或以上的基础库以使用云能力')
        } else {
            wx.cloud.init({
                // env 参数说明：
                //   env 参数决定接下来小程序发起的云开发调用（wx.cloud.xxx）会默认请求到哪个云环境的资源
                //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
                //   如不填则使用默认环境（第一个创建的环境）
                // env: 'my-env-id',
                traceUser: true,
            })
        }

        this.globalData = {
            flg: true,
            Cates: [],
            swiperList: [],
            ajaxTime: 0,
            BoardGameList:[],
            FoodList:[],
            login:false,
            openid:'',
            updatedata:[],
            couponList:[],
            ProductData:[]
        } 
        this.userinfo={}
        const CatesList = wx.getStorageSync('Cates')//分类数据
        const BoardGameList = wx.getStorageSync('BoardGameList')//桌游数据
        // 判断缓存中是否存在分类数据
            CatesList? this.globalData.Cates = CatesList.data :this.Database('MealData', "Cates", this, true)
        // 判断缓存中是否存在桌游数据
        this.Database('BoardGameList', "BoardGameList", this, true) 
        this.Database('UpdateDataTime', "updatedata", this, true)//获取更新数据时间
        this.Database('FoodData', "FoodList", this, true)//食品数据
        this.Database('coupon', "couponList", this, true)//优惠券数据
        this.Database('ProductData', "ProductData", this, true)//团购商品数据
        this.Login()
        setTimeout(() => {
            let AllData = []
            let BoardGameList = wx.getStorageSync('BoardGameList').data ||[]
            let ProductData = wx.getStorageSync('ProductData').data ||[]
            let FoodList = wx.getStorageSync('FoodList').data ||[]
            BoardGameList.forEach(v=>{
                AllData.push(v)
            })
            ProductData.forEach(v=>{
                AllData.push(v)
            })
            FoodList.forEach(v=>{
                v.children.forEach(v2=>{
                    AllData.push(v2)
                })
            })
            console.log(AllData);
            wx.setStorageSync('AllData', AllData)
        }, 5000);
    },
    Database(dataname, setname, that, flg) {//封装获取云函数方法
        // 加载数据时出现的提示框
        this.globalData.ajaxTime++
            wx.showLoading({
                title: "加载中",
                mask: true
            });

        var flg = flg | false
         wx.cloud.callFunction({
            // 云函数名称
            name: 'Database',
            data: {
                dataname: dataname,
            },
             success(res) {
                console.log(res.result.data)
                wx.setStorageSync(setname, { time: Date.now(), data: res.result.data })
                if (flg) {
                    that.globalData[setname] = res.result.data
                    if(dataname==="UpdateDataTime"){
                        that.UpdateData()
                    }
                } else {
                    that.setData({
                        [setname]: res.result.data
                    })
                }
            },
            fail: console.error,
            complete: () => {
                //当获取所有数据成功够移除提示框
                this.globalData.ajaxTime--
                    if (this.globalData.ajaxTime === 0) {
                        wx.hideLoading();
                    }
            }
        })
        
    },
    UpdateData(){
        const CatesList = wx.getStorageSync('Cates')//分类数据
        const BoardGameList = wx.getStorageSync('BoardGameList')//桌游数据
        // 判断缓存中是否存在分类数据
            this.globalData.updatedata[0].time<=CatesList.time? this.globalData.Cates = CatesList.data :this.Database('MealData', "Cates", this, true)
        // 判断缓存中是否存在桌游数据
        this.globalData.updatedata[0].time<=BoardGameList.time?this.globalData.BoardGameList = BoardGameList.data :this.Database('BoardGameList', "BoardGameList", this, true) 
        
    },
    cal(active,produits,that,num,hid){//封装好的添加到购物车的方法
        //参数1:是否选择好商品规格
        //参数2:需要添加的商品数据
        //参数3:需要设置的回的页面数据
        //参数4:加入购物车的数量
        //参数5:是否需要隐藏菜单
        if(this.globalData.login===false){
            wx.showToast({
              title: '请先登录',
              icon:"none"
            })
            setTimeout(function(){
                wx.switchTab({
                    url: '/pages/personal/index'
                  })
            },1000)
            if(hid){
                that.setData({
                    [hid]:true
                })
            }
            return false
        }
        if(active == false){
            wx.showToast({
                title: '请选择商品规格',
                icon:'none',
                duration: 1500,
                mask: true,
            })
            return
        }
        const cart = wx.getStorageSync("cart") || [];//获取本地存的购物车数据,不存在则为空数组
        let index = cart.findIndex(v => v.fid === produits.fid)//判断当前需要添加的对象是否已经存在购物车
        if (index === -1 ) {//当前商品不存在直接添加到本地购物车数据
            produits.num = num
            produits.checked = true
            cart.push(produits)
            this.Sus("cart", cart)//调用本地方法
        } else {//本地缓存中存在当前商品
            if ((cart[index].num + num) > 999) {//判断两次的值是否超过最大值
                cart[index].num = 999
                this.Sus("cart", cart)
            } else {
                cart[index].num = cart[index].num + num
                this.Sus("cart", cart)
            }
        }
        if(hid){
        that.setData({
            [hid]:true
        })
    }
    },
    Sus(name,data) { 
        let value={
            "shoppingCar":data
        }
        this.Update("users","_openid",this.globalData.openid,value)
        wx.setStorageSync(name, data);
        //成功后把数据穿回本地并提示用户加入购物车成功
        wx.showToast({
            title: '加入购物车成功',
            duration: 1500,
            mask: true,
        });
    },
    Update(dataname,name,value,data){
        //dataname:搜索的表名
        //name:搜索的对象名
        //value：对象名对应的值
        //data:需要更新的数据，形式{"xxx":"xxx"}
        wx.cloud.callFunction({
            name:"Update",
            data:{
                dataname:dataname,
                name:name,
                value:value,
                data:data
            },
            success:res=>{
                console.log(res);
                 
            } 
        })
    },
    MathNum(name,num,that,value){//封装好的计算组件
        //参数1:计算的方法
        //参数2:当前输入框的数量
        //参数3:需要设置回的原对象
        //参数4:文本框输入的值,可有可无
        if(name == "del"){
            if (--num < 1) {
                num = 1
                wx.showToast({
                    title: '不能再少啦',
                    icon: 'none',
                    duration: 1500,
                    mask: true,
                });
            }
        }else if(name == "add"){
            if (++num > 999) {
                num = 999
                wx.showToast({
                    title: '不能再多啦',
                    icon: 'none',
                    duration: 1500,
                    mask: true,
                });
            }
        }else if(name == "into"){
            that.setData({
                num: value
            })
            return
        }
        that.setData({
            num: num
        })
    },
    Login(){
        // 登录函数
        var that =this
        const db = wx.cloud.database()
        wx.cloud.callFunction({
            // 云函数名称
            name: 'login',
        }).then(res=>{
            that.globalData.openid = res.result.openid//设置当前用户的登录id

            db.collection("users").where({_openid:res.result.openid}).get().then(res=>{
                //查找关于当前用户的数据
                if(res.data.length!=0){//成功有数据后设置回全局对象
                that.userinfo = Object.assign(that.userinfo,res.data[0])
                that.globalData.login =true//登录状态为已登录
                wx.setStorageSync('cart', that.userinfo.shoppingCar)//设置内存中购物车数据
                wx.setStorageSync('orders', that.userinfo.orders)
                wx.setStorageSync('coupons', that.userinfo.coupons)
                wx.setStorageSync('favorite', that.userinfo.favorite)
            }
            })
        })
    },
    newDate(){
        var date = new Date()
         var y = date.getFullYear();  
          var m = date.getMonth() + 1;  
          m = m < 10 ? ('0' + m) : m;  
          var d = date.getDate();  
          d = d < 10 ? ('0' + d) : d;  
          var h = date.getHours();  
          h=h < 10 ? ('0' + h) : h;  
          var minute = date.getMinutes();  
          minute = minute < 10 ? ('0' + minute) : minute;  
          var second=date.getSeconds();  
          second=second < 10 ? ('0' + second) : second;  
          
          return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;  
},
orderBtn(name,ordernum,_that,flg){
    var that = this
    var content
    if(name ==="del"){
      content ='删除之后无法找回，是否确认？'
    }
    if(name ==="check"){
      content = "是否确认已使用？"
    }
        wx.showModal({
            title: '提示',
            content: content,
            showCancel: true,
            cancelText: '取消', 
            confirmText: '确定',
            success: (res) => {
                if (res.confirm) {
                  let orders = wx.getStorageSync('orders')//获取本地存储的订单信息
                  let index = orders.findIndex(v=>{ return v.num==ordernum})//获取当前订单号对应存储订单信息的下标
                  if(name ==="del"){
                    orders.splice(index, 1)//删除对应订单信息
                  }
                  if(name ==="check"){
                    orders[index].state = "used"
                    orders[index].finishtime = that.newDate()
                  }
                  wx.setStorageSync('orders', orders)//存回本地订单信息
                  let value={ //更新数据库的参数
                    "orders":orders
                }
                if(flg){
                    _that.triggerEvent('setvalue')
                _that.setData({value:_that.properties.orders})
                }else{
                    _that.setvalue()
                }
                
                that.Update("users","_openid",that.globalData.openid,value)//调用app封装好的方法执行云函数
                }
            },
            complete: () => {}
        });
    
},
DelShoppingCar(){
    let cart = wx.getStorageSync('cart')
    for (let i = cart.length -1; i >=0; i--) {
      if (cart[i].checked == true) {
          cart.splice(i, 1)
      }
    } 
    wx.setStorageSync('cart', cart)
    let value={
      "shoppingCar":cart
  }
  this.Update("users","_openid",this.globalData.openid,value)
    
},
Favorite(val){
    let favorite = wx.getStorageSync('favorite') ||[]
    let index = favorite.findIndex(v=>{return v.fid===val.fid})
    let flg = false
    if(index>-1){
        favorite.splice(index,1)
        wx.showToast({
          title: '取消收藏成功',
        })
        flg = false
    }else{
        favorite.push(val)
        wx.showToast({
            title: '添加收藏成功',
        })
        flg = true
    }
    wx.setStorageSync('favorite', favorite)
    let value={
        "favorite":favorite
    }
    this.Update("users","_openid",this.globalData.openid,value)
    return flg
}
})